package com.example.fengshoutong.adapter;

import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fengshoutong.R;
import com.example.fengshoutong.bean.Good;
import com.example.fengshoutong.utils.Constant;
import com.example.fengshoutong.utils.FragmentUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品适配器
 */
public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> {
    private List<Good> mDataList = new ArrayList<>();

    public GoodsAdapter(List<Good> dataList) {
        this.mDataList = dataList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_goods, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Good data = mDataList.get(position);
        holder.image_goods.setImageURI(Uri.parse(data.getImageUri()));
        holder.label_goods.setText(data.getLabel());
        holder.price_goods.setText(data.getPrice());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 保存当前点击的商品到全局变量中，跳转到商品页面
                Constant.currentGood = data;
                FragmentUtils.getInstance().switchFragment(R.id.nav_good);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mDataList != null) {
            return mDataList.size();
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView image_goods;
        TextView label_goods;
        TextView price_goods;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            image_goods = itemView.findViewById(R.id.image_goods);
            label_goods = itemView.findViewById(R.id.label_goods);
            price_goods = itemView.findViewById(R.id.price_goods);
        }
    }
}
